module ProblemsHelper
    def get_problem_state(problem, contest = nil)
      if(!logged_in?)
        return "neutral"
      end
      succ, unsucc = 0, 0
      problem_runs(problem, contest, true).each do |r|
        if r.user == current_user
          if r.status == "Accepted"
            succ = succ + 1
          else
            unsucc = unsucc + 1
          end
        end
      end
      if(succ > 0)
        return "solved"
      end
      if(unsucc > 0)
        return "tried"
      end
      "neutral"
    end
    
    def get_problem_succ_count(problem, contest = nil)
      if contest.nil?
         Run.count(:conditions => {:problem_id => problem, :status => "Accepted"}, :group => "user_id").size
      else
         problem_runs(problem, contest, false).select{|p| p.status == "Accepted"}.collect{|r| r.user}.uniq.size
      end
    end
    
    def get_problem_succ_rate(problem, contest = nil)
      all_submits_count = problem_runs(problem, contest, false).size
      return 0 if all_submits_count == 0
      acc_runs = problem_runs(problem, contest, false).select{|r| r.status == "Accepted"}.size
      ((acc_runs.to_f * 100.0) / all_submits_count.to_f).round #converting to percents
    end
    
    def problem_runs(problem, contest, without_end)
      if contest.nil?
        problem.runs
      else
        if(!without_end)
          problem.runs.select{|r| r.created_at >= contest.start_time && r.created_at <= contest.end_time}
        else
          problem.runs.select{|r| r.created_at >= contest.start_time}
        end
      end
    end 
end
